import React, { PureComponent } from 'react'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

export default class index extends PureComponent {

  //通过请求获取文件blob格式
  getFileBlob = (url) => {
    return new Promise((resolve, reject) => {
        let request = new XMLHttpRequest()
        request.open("GET", url, true)
        request.responseType = "blob"
        request.onload = (res) => {
            if (res.target.status === 200) {
                resolve(res.target.response)
            } else {
                reject(res)
            }
        }
        request.send()
    })
  }
  
  downLoad = () => {
    const zip = new JSZip()
    let result = []
    let files = [
        "https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/C13012345678/1645261335302/测试文档.doc",
        "https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/lilinjian/1641631041478/dd.txt",
        "https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/C13012345678/1650420333942/123.xls",
        "https://im-1305783521.cos.ap-guangzhou.myqcloud.com/im/file/C13012345678/1641805597561/巴达兽.png",
        "http://localhost:3002/favicon.ico",
    ]
    for (let i in files) {
        let promise = this.getFileBlob(files[i]).then((res) => {
            const fileName = files[i].split('/')[files[i].split('/').length - 1]
            const name = fileName.substring(0, fileName.lastIndexOf("."))
            let format = files[i].substring(files[i].lastIndexOf("."), files[i].length)
            zip.file(name + format, res, { binary: true })
        })
        result.push(promise)
    }
    Promise.all(result).then(() => {
        zip.generateAsync({ type: "blob" }).then((res) => {
            saveAs(res, "文件.zip")
        })
    })
  }

  downloadSingle = () => {
    let a = document.createElement("a");//创建a标签
    const href = 'http://localhost:3000/static/facial/face.obj'
    a.setAttribute("href", href);//设置文件下载地址
    a.setAttribute('download', '模型.obj');
    // a.setAttribute("href", href.replace('http','https'));//设置文件下载地址
    // a.setAttribute('target', '_blank');//在当前页面创建下载
    document.body.appendChild(a);//添加到body
    a.click();//触发事件
    document.body.removeChild(a);//移除标签
  }
  render() {
    return (
      <div>
        <button onClick={this.downLoad}>下载多个文件</button>
      </div>
    )
  }
}
